660A - Co-prime Array - CodeForces Solution


greedy implementation math number theory *1200

Please click on ads to support us..

Python Code:

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a


def solution():
    n = int(input())
    vals = list(map(int, input().split()))
    if n == 1:
        print(0)
        print(*vals)
    else:
        i = 0
        c = 0
        while i < n-1:
            if gcd(vals[i], vals[i+1]) != 1:
                vals.insert(i+1, 1)
                n += 1
                c += 1
            i += 1
        print(c)
        print(*vals)


t = 1
while t:
    t -= 1
    solution()

	  			   		 							 	    				 	

C++ Code:

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
    ll n;
    cin>>n;
    vector<ll>a(n);
    for(ll i=0;i<n;i++)cin>>a[i];
    
    vector<ll>ans;
    ans.push_back(a[0]);
    
    for(ll i=1;i<n;i++){
        if(__gcd(a[i-1],a[i])!=1)
            ans.push_back(1);
        ans.push_back(a[i]);
    }
    cout<<ans.size()-n<<endl;
    for(auto num : ans)
    cout<<num<<" ";
    cout<<endl;
}


Comments

Submit
0 Comments
More Questions

227B - Effective Approach
1534B - Histogram Ugliness
1611B - Team Composition Programmers and Mathematicians
110A - Nearly Lucky Number
1220B - Multiplication Table
1644A - Doors and Keys
1644B - Anti-Fibonacci Permutation
1610A - Anti Light's Cell Guessing
349B - Color the Fence
144A - Arrival of the General
1106A - Lunar New Year and Cross Counting
58A - Chat room
230A - Dragons
200B - Drinks
13A - Numbers
129A - Cookies
1367B - Even Array
136A - Presents
1450A - Avoid Trygub
327A - Flipping Game
411A - Password Check
1520C - Not Adjacent Matrix
1538B - Friends and Candies
580A - Kefa and First Steps
1038B - Non-Coprime Partition
43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet